package com.yangquan.ayuan.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class MyAtomicInteger {
    private volatile int value;

    private static final Unsafe unsafe;
    private static final long valueOffset;

    // 初始化 Unsafe 实例和字段偏移
    static {
        try {
            // 通过反射获取 Unsafe 实例
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);

            // 获取 value 字段的偏移地址
            valueOffset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (Exception e) {
            throw new Error(e);
        }
    }

    // 构造函数
    public MyAtomicInteger(int initialValue) {
        this.value = initialValue;
    }

    // CAS 操作
    public final boolean compareAndSet(int expect, int update) {
        return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
    }

    // 获取当前值
    public int get() {
        return value;
    }

    // 原子 +1
    public void increment() {
        int oldValue, newValue;
        do {
            oldValue = get();
            newValue = oldValue + 1;
        } while (!compareAndSet(oldValue, newValue));
    }
}